<template>
	<div class="auth-page">
		<div class="container page">
			<div class="row">
				<div class="col-md-6 offset-md-3 col-xs-12">
					<h1 class="text-xs-center">{{isLogin ? 'Sign in' : 'Sign up'}}</h1>
					<p class="text-xs-center">
						<!-- <a href>Have an account?</a> -->
						<nuxt-link v-if="isLogin" to="/register">Needs an account?</nuxt-link>
						<nuxt-link v-else to="/login">Have an account?</nuxt-link>
					</p>

					<ul class="error-messages">
						<template v-for="(item,filed) in error">
							<li v-for="(message,index) in item" :key="index">{{filed}}:{{message}}</li>
						</template>
					</ul>

					<form @submit.prevent="onSubmit">
						<fieldset class="form-group" v-if="!isLogin">
							<input
								class="form-control form-control-lg"
								type="text"
								placeholder="Your Name"
								v-model="user.username"
								required
							/>
						</fieldset>
						<fieldset class="form-group">
							<input
								class="form-control form-control-lg"
								type="text"
								v-model="user.email"
								placeholder="Email"
								required
							/>
						</fieldset>
						<fieldset class="form-group">
							<input
								class="form-control form-control-lg"
								type="password"
								v-model="user.password"
								placeholder="Password"
								minlength="8"
								required
							/>
						</fieldset>
						<button v-if="isLogin" class="btn btn-lg btn-primary pull-xs-right">Sign in</button>
						<button v-else class="btn btn-lg btn-primary pull-xs-right">Sign up</button>
					</form>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
import { login, register } from "@/api/user";
const Cookie = process.client ? require('js-cookie') : undefined
export default {
    middleware:'noauthenticated',
	computed: {
		isLogin() {
			return this.$route.name == "login";
		},
	},
	data() {
		return {
			user: {
				username: "",
				email: "",
				password: "",
			},
			error: {},
		};
	},
	methods: {
		async onSubmit() {
			try {
				const { data } = this.isLogin
					? await login({
							user: this.user,
					  })
					: await register({
							user: this.user,
					  });
				console.log(data);
				// 保存用户的登录状态 前后盾共享登录状态
                this.$store.commit('setUser',data.user)
                //为了刷新页面状态丢失，需要把数据持久化，服务端共享登录状态
                Cookie.set('user',data.user)
                //登陆之后跳到首页
				this.$router.push("/");
			} catch (error) {
				this.error = error.response.data.errors;
			}
		},
	},
};
</script>

<style>
</style>